package com.forezp.configclient.logMQ;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version V1.0  </br>
 * @ClassName ReceiveLogsTopicForKernel </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 11/23/2018 3:13 PM</br>
 */
public class ReceiveLogsTopicForKernel {
    public static final String EXCHANGE = "topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 声明转发器
        channel.exchangeDeclare(EXCHANGE,"topic");
        // 随机生成一个队列
        String queueName = channel.queueDeclare().getQueue();
        //接收所有与kernel相关的消息
        channel.queueBind(queueName, EXCHANGE,"kernel.*");
        System.out.println(" [*] Waiting for messages about kernel. To exit press CTRL+C");
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println(" [x] Received routingKey = " + envelope.getRoutingKey()
                        + ",msg = " + msg + ".");
            }
        };
        channel.basicConsume(queueName, true,consumer);
    }
}
